import axios from 'axios'
import { Message, Loading} from 'element-ui'

//加载信息
let loding =null

function startLoading () {
  return loding = Loading.service({
    lock: true,
    text: '加载中...',
    background: "rgba(0, 0, 0, 0.7)"
  })
}
//关闭加载信息
function endLoading () {
  loding.close()
}

//注册全部地址
const baseURL = 'http://192.168.1.8:8080'

const version = ''
//创建axios实例
const instance = axios.create({
  baseURL: baseURL+version,
  timeout: 3000,
  
})

//请求拦截器
instance.interceptors.request.use(
  function (config) {
        // 加载
        startLoading();
        //配置全局token
        config.headers.token = window.localStorage.getItem('token')
        // config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
        // config.url = (/http(s?):\/\//.test(config.url) ? '' : '/admin') + config.url
        if(config.method.toLowerCase() === 'get'){
          // 增加时间戳 避免GET请求的时候IE缓存
          const timestamp = new Date().getTime()
          config.url += config.url.indexOf('?') !== -1 ? `&_=${timestamp}` : `?_=${timestamp}`
       }
       return config
  },
  function (error) {
    return Promise.reject(error);
  }
 )

//响应拦截器

instance.interceptors.response.use(
  function (response) {
    endLoading();
    if (response.data.code == 0) {
      //成功
      let  { data } = response
      console.log('----reaponse',data)
      
      return data
    }else{
      if(response.data.code == 400){
        //未登录或登陆过期
        window.location.href = '/login'
      }else{
        //出错
      Message.error(response.data.msg ? response.data.msg : '请求出错，请重试')
      }
    }
  },function (error) {
    // 错误提醒
    endLoading();
    
    console.log(error)
    return Promise.reject(error);
  })

  export default instance

  export function arrayToTree(list, parentId = null) {
    return list
        .filter(item => item.parentId === parentId)
        .map(item => ({
            ...item,
            children: arrayToTree(list, item.id),
        }))
}

export const baseUrl = baseURL